# encoding=utf8
from __future__ import division
from requests.auth import HTTPBasicAuth
import requests
import xlwt
import sys
import time

"""
Date        : 2022-10-24
Author      : Jimmy
CopyRight   : Jfrog China
"""
author_value = 'Basic ZnhtOkppbW15MjAyMkBKZnJvZw=='
# 根据现场环境修改下面三行即可，token在artifactory管理系统设置或者赋值为APIKey
web_url = "http://your.web.site:31645"
user_name = 'fxm'
# token = 'eyJ2ZXIiOiIyIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYiLCJraWQiOiJ1TUJwdFM1ZGdTWTR3VWk2QWFBenN6R1pvdGd4NGF0dHNKQXFpeGpfOXNNIn0.eyJleHQiOiJ7XCJyZXZvY2FibGVcIjpcInRydWVcIn0iLCJzdWIiOiJqZmFjQDAxZ2Nkc2R0YjJmZDlxMDBwMXR0YnQxYzF3XC91c2Vyc1wvZnhtIiwic2NwIjoiYXBwbGllZC1wZXJtaXNzaW9uc1wvdXNlciIsImF1ZCI6IipAKiIsImlzcyI6ImpmZmVAMDAwIiwiZXhwIjoxNjk4NDY1MjE0LCJpYXQiOjE2NjY5MjkyMTQsImp0aSI6ImVlNWU0ODc5LTU2YWQtNGQ5Ny05NzQ1LTJlOGQzOTVmZWZiYyJ9.RoCxU0eswhlPwOsWmABL9sw4M_srW1euniGlKYZ0UqQwo8pEXHXysIu3MyYe6PE-l3yUpYwOblFLl7oFFRAVPlVUjhIU3x54RL2zS8k1fOAwRCwz78GgYLlDkbEyqhcOIOSIgxEx_i8YUg-VKp11n_KqTZvLJB63kWELuYIyRwVCQjqwW40wtdz4dTKIiYEjr_ZofvMPt974TT5vuoMP2pkht_RwyCg6PzUGZAnlAW_TADedHj8IRmZXAhrb6qmF-fraSUsV1rC8w54IYMzKJrpBBiv93SwUv0lvmWLwi37z46bHARIifyNOcDPeG_p0Pf8BsjZ1UE04pz7uHmCHLA'
token = 'AP8ixxGxt8hpwtGigQ8wBfPsDGz'


def get_downloads_by_name(args):
    try:
        if args['path'] == ".":
            download_url = web_url + "/artifactory/api/storage/" \
                           + args['repo'] + "/" + args['name'] + "?stats"
        else:
            download_url = web_url + "/artifactory/api/storage/" \
                           + args['repo'] + "/" + args['path'] + "/" + args['name'] + "?stats"
        headers = {
            'Authorization': author_value
        }
        # get_response = requests.get(download_url, headers=headers)
        get_response = requests.get(download_url, auth=HTTPBasicAuth(user_name, token))
        return get_response.json()['downloadCount']
    except Exception as e:
        print(e, "**********Error************\n make sure your repository's type is maven")
        sys.exit()


def get_jar_size_by_byte(param):
    if param < 1024:
        return str(param) + " B"
    if 1024 > float(param) / 1024 > 1:
        return str(round(param / 1024, 2)) + " KB"
    if 1024 > float(param) / 1024 / 1024 > 1:
        return str(round(param / 1024 / 1024, 2)) + " MB"
    if 1024 > float(param) / 1024 / 1024 / 1024 > 1:
        return str(round(param / 1024 / 1024 / 1024, 2)) + " GB"
    else:
        return "Error"


def get_module_id_by_path(path):
    if "/" in path and len(path.split('/')) > 2:
        tmp_array = path.split('/')
        version = tmp_array[len(tmp_array) - 1]
        artifact_id = tmp_array[len(tmp_array) - 2]
        tmp_array.remove(tmp_array[len(tmp_array) - 1])
        tmp_array.remove(tmp_array[len(tmp_array) - 1])
        module_id = ".".join(tmp_array) + ":" + artifact_id + ":" + version
        return module_id
    else:
        return ""


if len(sys.argv) < 2:
    print('missing param')

# 创建xls
workbook = xlwt.Workbook(encoding="utf-8")
local_time = time.localtime(time.time())
now = time.strftime("%Y-%m-%d_%H:%M:%S", local_time)
sheet = workbook.add_sheet(sys.argv[1])
# 写入标题
for col, column in enumerate(["name", "path", "created", "modified", "downloads", "size", "moduleId"]):
    sheet.write(0, col, column)

pageSize = 1000
row = 0
sheet_row_num = 60000
for pageNum in range(0, 1000):
    offset = pageNum * pageSize
    url = web_url + "/artifactory/api/search/aql"
    payload = "items.find(    {\n        \"repo\":{\"$eq\":\"" + sys.argv[
        1] + "\"}    "
    if len(sys.argv) == 3:
        payload = payload + ",\"path\":{\"$match\":\"" + sys.argv[2] + "\"}"
    payload = payload + "}).offset(" + str(offset) + ").limit(" + str(pageSize) + ")"
    headers = {
        'Authorization': author_value,
        'Content-Type': 'text/plain'
    }
    # response = requests.request("POST", url, headers=headers, data=payload,auth=HTTPBasicAuth(user_name,token))
    response = requests.request("POST", url, data=payload, auth=HTTPBasicAuth(user_name, token))
    json_result = response.json()
    if len(json_result['results']) == 0:
        break
    else:
        # 循环获取文件基本信息，写入到xls文件中
        for data in json_result['results']:
            row = row + 1
            if row <= sheet_row_num:
                # 根据jar文件名称调用另外一个接口，获取下载次数信息
                downloads = get_downloads_by_name(data)
                sheet.write(row, 0, data['name'])
                sheet.write(row, 1, data['path'])
                sheet.write(row, 2, data['created'])
                sheet.write(row, 3, data['modified'])
                sheet.write(row, 4, downloads)
                sheet.write(row, 5, get_jar_size_by_byte(data['size']))
                if ".jar" in data['name']:
                    sheet.write(row, 6, get_module_id_by_path(data['path']))
                if row == sheet_row_num:
                    sheet1 = workbook.add_sheet(sys.argv[1] + '_1')
                    for col, column in enumerate(
                            ["name", "path", "created", "modified", "downloads", "size", "moduleId"]):
                        sheet1.write(0, col, column)
            elif sheet_row_num < row <= sheet_row_num * 2:
                # 根据jar文件名称调用另外一个接口，获取下载次数信息
                downloads = get_downloads_by_name(data)
                sheet1.write(row - sheet_row_num, 0, data['name'])
                sheet1.write(row - sheet_row_num, 1, data['path'])
                sheet1.write(row - sheet_row_num, 2, data['created'])
                sheet1.write(row - sheet_row_num, 3, data['modified'])
                sheet1.write(row - sheet_row_num, 4, downloads)
                sheet1.write(row - sheet_row_num, 5, get_jar_size_by_byte(data['size']))
                if ".jar" in data['name']:
                    sheet1.write(row - sheet_row_num, 6, get_module_id_by_path(data['path']))
                if row == sheet_row_num * 2:
                    sheet2 = workbook.add_sheet(sys.argv[1] + '_2')
                    for col, column in enumerate(
                            ["name", "path", "created", "modified", "downloads", "size", "moduleId"]):
                        sheet2.write(0, col, column)
            elif sheet_row_num * 2 < row <= sheet_row_num * 3:
                # 根据jar文件名称调用另外一个接口，获取下载次数信息
                downloads = get_downloads_by_name(data)
                sheet2.write(row - sheet_row_num * 2, 0, data['name'])
                sheet2.write(row - sheet_row_num * 2, 1, data['path'])
                sheet2.write(row - sheet_row_num * 2, 2, data['created'])
                sheet2.write(row - sheet_row_num * 2, 3, data['modified'])
                sheet2.write(row - sheet_row_num * 2, 4, downloads)
                sheet2.write(row - sheet_row_num * 2, 5, get_jar_size_by_byte(data['size']))
                if ".jar" in data['name']:
                    sheet2.write(row - sheet_row_num * 2, 6, get_module_id_by_path(data['path']))
                if row == sheet_row_num * 3:
                    sheet3 = workbook.add_sheet(sys.argv[1] + '_3')
                    for col, column in enumerate(
                            ["name", "path", "created", "modified", "downloads", "size", "moduleId"]):
                        sheet3.write(0, col, column)
            elif sheet_row_num * 3 < row:
                # 根据jar文件名称调用另外一个接口，获取下载次数信息
                downloads = get_downloads_by_name(data)
                sheet3.write(row - sheet_row_num * 3, 0, data['name'])
                sheet3.write(row - sheet_row_num * 3, 1, data['path'])
                sheet3.write(row - sheet_row_num * 3, 2, data['created'])
                sheet3.write(row - sheet_row_num * 3, 3, data['modified'])
                sheet3.write(row - sheet_row_num * 3, 4, downloads)
                sheet3.write(row - sheet_row_num * 3, 5, get_jar_size_by_byte(data['size']))
                if ".jar" in data['name']:
                    sheet3.write(row - sheet_row_num * 3, 6, get_module_id_by_path(data['path']))
            else:
                print('the total number is more than 24w')
if row == 0:
    print("**********Error************\n Make sure your repository exists and is not empty!!!!!")
else:
    workbook.save(sys.argv[1] + now + ".xls")
    print('========Finished===========')
